package com.ayano.ayanoOJ.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.ayano.ayanoOJ.common.ErrorCode;
import com.ayano.ayanoOJ.constant.CommonConstant;
import com.ayano.ayanoOJ.exception.BusinessException;
import com.ayano.ayanoOJ.model.dto.question.QuestionQueryRequest;
import com.ayano.ayanoOJ.model.dto.questionsubmit.QuestionSubmitAddRequest;
import com.ayano.ayanoOJ.model.dto.questionsubmit.QuestionSubmitQueryRequest;
import com.ayano.ayanoOJ.model.entity.Question;
import com.ayano.ayanoOJ.model.entity.QuestionSubmit;
import com.ayano.ayanoOJ.model.entity.User;
import com.ayano.ayanoOJ.model.enums.QuestionSubmitLanguageEnum;
import com.ayano.ayanoOJ.model.enums.QuestionSubmitStatusEnum;
import com.ayano.ayanoOJ.model.vo.QuestionSubmitVO;
import com.ayano.ayanoOJ.model.vo.QuestionVO;
import com.ayano.ayanoOJ.model.vo.UserVO;
import com.ayano.ayanoOJ.service.QuestionService;
import com.ayano.ayanoOJ.service.QuestionSubmitService;
import com.ayano.ayanoOJ.service.UserService;
import com.ayano.ayanoOJ.utils.SqlUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ayano.ayanoOJ.mapper.QuestionSubmitMapper;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author chenajiajun
 * @description 针对表【question_submit(题目提交)】的数据库操作Service实现
 * @createDate 2024-12-10 13:26:49
 */
@Service
public class QuestionSubmitServiceImpl extends ServiceImpl<QuestionSubmitMapper, QuestionSubmit> implements QuestionSubmitService {

    @Resource
    private QuestionService questionService;

    @Resource
    private UserService userService;

    /**
     * 提交题目
     *
     * @param questionSubmitAddRequest
     * @param loginUser
     * @return
     */
    @Override
    public long doQuestionSubmit(QuestionSubmitAddRequest questionSubmitAddRequest, User loginUser) {
        // 校验编程语言是否合法
        String language = questionSubmitAddRequest.getLanguage();
        // getEnumByValue(language) 获取对应的枚举值
        QuestionSubmitLanguageEnum languageEnum = QuestionSubmitLanguageEnum.getEnumByValue(language);
        if (languageEnum == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "编程语言错误");
        }
        // 获取题目 id
        long questionId = questionSubmitAddRequest.getQuestionId();
        // 根据题目 id 获取题目
        Question question = questionService.getById(questionId);
        if (question == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }

        // 将用户提交的题目插入到数据库
        long userId = loginUser.getId();
        QuestionSubmit questionSubmit = new QuestionSubmit();
        questionSubmit.setUserId(userId);
        questionSubmit.setQuestionId(questionId);
        questionSubmit.setCode(questionSubmitAddRequest.getCode());
        questionSubmit.setLanguage(language);
        // 设置初始状态 0 - 等待中
        questionSubmit.setStatus(QuestionSubmitStatusEnum.WAITING.getValue());
        questionSubmit.setJudgeInfo("{}");
        // save() 插入数据库
        boolean save = this.save(questionSubmit);
        if (!save) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "数据插入失败");
        }
//        // AopContext.currentProxy() 获取当前事务代理 能用本类的 Service 调用本类的方法
//        QuestionSubmitService questionSubmitService = (QuestionSubmitService) AopContext.currentProxy();
//        // 锁必须要包裹住事务方法
//        // String.valueOf() 转换为字符串
//        // intern() 如果常量池中有直接返回，如果没有将其添加到常量池在返回
//        // 用 userId 做标识，同一用户只有一个进程能进入锁
//        synchronized (String.valueOf(userId).intern()) {
//            return questionSubmitService.doQuestionSubmitInner(userId, questionId);
//        }
        return questionSubmit.getId();
    }


    /**
     * 获取查询包装类(用户根据哪些字段查询,根据前端传来的请求对象，得到 mybatis 框架支持的查询类 QueryWrapper 类)
     *
     * @param questionSubmitQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<QuestionSubmit> getQueryWrapper(QuestionSubmitQueryRequest questionSubmitQueryRequest) {
        QueryWrapper<QuestionSubmit> queryWrapper = new QueryWrapper<>();
        if (questionSubmitQueryRequest == null) {
            return queryWrapper;
        }
        String language = questionSubmitQueryRequest.getLanguage();
        Integer status = questionSubmitQueryRequest.getStatus();
        Long questionId = questionSubmitQueryRequest.getQuestionId();
        Long userId = questionSubmitQueryRequest.getUserId();
        // 排序字段
        String sortField = questionSubmitQueryRequest.getSortField();
        // 排序顺序（默认升序）
        String sortOrder = questionSubmitQueryRequest.getSortOrder();

        // 凭借查询条件
        queryWrapper.eq(StringUtils.isNotBlank(language), "language", language);
        queryWrapper.eq(ObjectUtils.isNotEmpty(questionId), "questionId", questionId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(QuestionSubmitStatusEnum.getEnumByValue(status) != null, "status", status);
        queryWrapper.eq("isDelete", false);

        // orderBy(如果没有特殊字符就是true，默认升序，要排序的字段) 将查询到的结果进行排序
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC), sortField);
        return queryWrapper;
    }

    @Override
    public QuestionSubmitVO getQuestionSubmitVO(QuestionSubmit questionSubmit, User loginUser) {
        QuestionSubmitVO questionSubmitVO = QuestionSubmitVO.objToVo(questionSubmit);
        // 仅本人和管理员能看见自己（提交userId和登录用户id不同）提交的代码
        long userId = loginUser.getId();
        // 处理脱敏
        if (userId != questionSubmitVO.getUserId() && !userService.isAdmin(loginUser)) {
            questionSubmitVO.setCode(null);
        }
        return questionSubmitVO;
    }

    @Override
    public Page<QuestionSubmitVO> getQuestionSubmitVOPage(Page<QuestionSubmit> questionSubmitPage, User loginUser) {
        // 从 questionSubmitPage 中获取所有数据
        List<QuestionSubmit> questionSubmitList = questionSubmitPage.getRecords();
        // 创建Page VO
        Page<QuestionSubmitVO> questionSubmitVOPage = new Page<>(questionSubmitPage.getCurrent(), questionSubmitPage.getSize(), questionSubmitPage.getTotal());
        if (CollUtil.isEmpty(questionSubmitList)) {
            return questionSubmitVOPage;
        }
        // 对所有数据进行脱敏
        List<QuestionSubmitVO> questionSubmitVOList = questionSubmitList.stream()
                .map(questionSubmit -> getQuestionSubmitVO(questionSubmit, loginUser))
                .collect(Collectors.toList());
        // 把所有数据插入 Page VO
        questionSubmitVOPage.setRecords(questionSubmitVOList);
        return questionSubmitVOPage;
    }
}




